package com.nulldev.util.web.nTube.util;

import java.util.List;

import com.nulldev.util.io.IOUtils;
import com.nulldev.util.web.YouTubeExtractor.formats.AudioCodec;
import com.nulldev.util.web.YouTubeExtractor.formats.VideoCodec;
import com.nulldev.util.web.YouTubeExtractor.video.YouTubeVideo;

import static com.nulldev.util.web.nTube.pages.Urlizer.urlizer;

public class M3U8LiveStreamGenerator {

	public static String make(final List<YouTubeVideo> video) {
		return make(video, false);
	}

	public static String make(final List<YouTubeVideo> video, final boolean useUrlizer) {
		final StringBuilder b = new StringBuilder(IOUtils.STRING_ALLOC_BUFFER);
		b.append("#EXTM3U\n");
		b.append("#EXT-X-TARGETDURATION:6\n");
		b.append("#EXT-X-VERSION:1\n");
		for (final YouTubeVideo vid : video) {
			if (vid == null || vid.getFormat() == null)
				continue;
			if (vid.getFormat().getVideoCodec() == VideoCodec.NONE)
				continue;
			if (vid.getFormat().getAudioCodec() != AudioCodec.NONE)
				continue;
			b.append("#EXTINF:" + vid.getFormat().getLiveStreamTargetDuration() + ",\n");
			b.append("#EXT-X-STREAM-INF:BANDWIDTH=" + vid.getBitrate() + ",RESOLUTION=" + vid.getFormat().getWidth() + "x" + vid.getFormat().getHeight()
					+ ",CODECS=\"" + vid.getPrettyMime() + "\"" + ",FRAME-RATE=" + vid.getFPS() + "\n");
			b.append((useUrlizer ? urlizer(vid.videoURL()) : vid.videoURL()) + "\n");
		}
		return b.toString();
	}
}
